package com.code.services.impl;

import com.code.consts.CommonConsts;
import com.code.daos.robot.CheckFailureMapper;
import com.code.daos.robot.RobotTaskCheckMapper;
import com.code.enums.ResultCode;
import com.code.enums.RewardKeyEnum;
import com.code.exceptions.BusinessException;
import com.code.managers.HttpManager;
import com.code.models.qo.AgentRankQO;
import com.code.models.qo.InviterQO;
import com.code.models.qo.RobotTaskCheckQO;
import com.code.models.robot.*;
import com.code.models.vo.*;
import com.code.services.*;
import com.code.utils.SnowFlakeIdUtil;
import com.code.utils.TimeUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 机器人任务审核服务实现类
 *
 * @author xiaoyaowang
 */
@Service
@Slf4j
public class RobotTaskCheckServiceImpl implements RobotTaskCheckService {

    @Resource
    RobotTaskCheckMapper robotTaskCheckMapper;

    @Resource
    RobotRewardFlowService robotRewardFlowService;

    @Resource
    RobotSystemService robotSystemService;

    @Resource
    RobotInviteService robotInviteService;

    @Resource
    RequestWalletService requestWalletService;

    @Resource
    ChatLinkService chatLinkService;

    @Resource
    ChatTwitterService chatTwitterService;

    @Resource
    CheckFailureMapper checkFailureMapper;

    @Resource
    HttpManager httpManager;

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = CommonConsts.TRANSACTION_MANAGER)
    public RobotTaskCheck updateRobotTaskState(RobotTaskCheck robotTaskCheckQuery) {
        Integer id = robotTaskCheckQuery.getId();
        RobotTaskCheck robotTaskCheck = robotTaskCheckMapper.getRobotTaskCheckById(id);
        if (null != robotTaskCheck) {
            Integer state = robotTaskCheckQuery.getState();
            if (null == state) {
                state = 0;
            }
            String chatId = robotTaskCheck.getChatId();
            if (state == 0) {
                if (null != robotTaskCheckMapper.existsChatBanByChatId(chatId)) {
                    robotTaskCheckMapper.deleteChatBanByChatId(chatId);
                }
                robotTaskCheckMapper.updateRobotTaskState(id, state, new Date());
            }
            // 审核成功，本人获取400TP，如果被邀请人也审核成功，则还可以额外获取100TP
            if (state == 2) {
//                if (!httpManager.verifyAuthorityByToken(RequestContextUtil.getRequest().getHeader("token"))) {
//                    throw new BusinessException(ResultCode.PERMISSION_NO_ACCESS);
//                }
                checkSuccess(chatId, id, state);
                return getRobotTaskCheckById(id);
            }
            // 审核失败
            if (state == 1) {
                // 删除第六步任务
                Integer sixthTaskId = robotTaskCheckMapper.getTaskIdBySort(6);
                RobotChatFinishTask robotChatFinishSixthTaskDb = robotTaskCheckMapper.getRobotChatFinishTaskByChatIdAndTaskId(chatId, sixthTaskId);
                if (null != robotChatFinishSixthTaskDb) {
                    robotTaskCheckMapper.deleteRobotChatFinishTask(robotChatFinishSixthTaskDb);
                }
                // 第一步：（第五步任务）删除用户之前完成的发送不合格截图任务
                Integer fifthTaskId = robotTaskCheckMapper.getTaskIdBySort(5);
                RobotChatFinishTask robotChatFinishFifthTaskDb = robotTaskCheckMapper.getRobotChatFinishTaskByChatIdAndTaskId(chatId, fifthTaskId);
                if (null != robotChatFinishFifthTaskDb) {
                    robotTaskCheckMapper.deleteRobotChatFinishTask(robotChatFinishFifthTaskDb);
                }
                // 第二步：（第五步任务）删除审核记录和图片审核记录
                if (null != robotTaskCheckMapper.selectByPrimaryKey(id)) {
                    RobotTaskCheck robotTaskCheckDb = new RobotTaskCheck();
                    robotTaskCheckDb.setId(id);
                    robotTaskCheckMapper.deleteByPrimaryKey(robotTaskCheckDb);
                }
                List<RobotTaskCheckContent> robotTaskCheckContentList = robotTaskCheckMapper.getRobotTaskCheckContentListByTaskCheckId(id);
                if (!CollectionUtils.isEmpty(robotTaskCheckContentList)) {
                    robotTaskCheckMapper.deleteRobotTaskCheckContentList(robotTaskCheckContentList);
                }
                // 第四步：（第4步任务）删除关注推特的相关信息
                chatTwitterService.deleteChatTwitterByChatId(chatId);
                Integer fourthTaskId = robotTaskCheckMapper.getTaskIdBySort(4);
                RobotChatFinishTask robotChatFinishFourthTaskDb = robotTaskCheckMapper.getRobotChatFinishTaskByChatIdAndTaskId(chatId, fourthTaskId);
                if (null != robotChatFinishFourthTaskDb) {
                    robotTaskCheckMapper.deleteRobotChatFinishTask(robotChatFinishFourthTaskDb);
                }
                // （第三步任务）删除第三步任务完成记录
                Integer thirdTaskId = robotTaskCheckMapper.getTaskIdBySort(3);
                RobotChatFinishTask robotChatFinishThirdTaskDb = robotTaskCheckMapper.getRobotChatFinishTaskByChatIdAndTaskId(chatId, thirdTaskId);
                if (null != robotChatFinishThirdTaskDb) {
                    robotTaskCheckMapper.deleteRobotChatFinishTask(robotChatFinishThirdTaskDb);
                }
                // （第4步任务和第二步任务）删除关注推特的链接相关信息
                chatLinkService.deleteChatLinkByChatId(chatId);
                // （第二步任务）删除第二步任务完成记录
                Integer secondTaskId = robotTaskCheckMapper.getTaskIdBySort(2);
                RobotChatFinishTask robotChatFinishSecondTaskDb = robotTaskCheckMapper.getRobotChatFinishTaskByChatIdAndTaskId(chatId, secondTaskId);
                if (null != robotChatFinishSecondTaskDb) {
                    robotTaskCheckMapper.deleteRobotChatFinishTask(robotChatFinishSecondTaskDb);
                }
                // 最后一步：任务机器人向用户发送重新发送图片截图的任务
                String failureInfo = robotTaskCheckQuery.getFailureInfo();
                if (StringUtils.isBlank(failureInfo)) {
                    failureInfo = robotSystemService.getSystemValueBySystemKey(RewardKeyEnum.SEND_PHOTO_TASK.name());
                }
                CheckFailure checkFailure = new CheckFailure();
                checkFailure.setChatId(chatId);
                checkFailure.setDeleted(0);
                checkFailure.setCreatedAt(new Date());
                checkFailure.setUpdatedAt(new Date());
                checkFailureMapper.insert(checkFailure);
                httpManager.sendReSendPhoto(Long.parseLong(chatId), failureInfo);
            }
            // 已封禁
            if (state == 3) {
                // 修改状态为已封禁
                int count = robotTaskCheckMapper.updateRobotTaskState(id, state, new Date());
                if (count > 0) {
                    // 任务机器人向用户发送封禁的原因
                    httpManager.sendReSendPhoto(Long.parseLong(robotTaskCheck.getChatId()), robotSystemService.getSystemValueBySystemKey(RewardKeyEnum.BAN.name()));
                }
            }
        }
        return robotTaskCheckMapper.getRobotTaskCheckById(id);
    }

    @Override
    public PageInfo<RobotTaskCheck> getRobotTaskCheckListByPage(RobotTaskCheckQO robotTaskCheckQO) {
        Integer sort = robotTaskCheckQO.getSort();
        if (null == sort) {
            robotTaskCheckQO.setSort(2);
        }
        Integer pageNum = robotTaskCheckQO.getPageNum();
        Integer pageSize = robotTaskCheckQO.getPageSize();
        PageHelper.startPage(pageNum, pageSize);
        List<RobotTaskCheck> list;
        Integer bzTaskFinishState = robotTaskCheckQO.getBzTaskFinishState();
        if (null != bzTaskFinishState) {
            list = robotTaskCheckMapper.getRobotTaskCheckListWithBzByPage(robotTaskCheckQO);
        } else {
            list = robotTaskCheckMapper.getRobotTaskCheckListByPage(robotTaskCheckQO);
        }
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(item -> {
                if (null == item.getAgentState()) {
                    item.setAgentState(0);
                }
                if (null != robotTaskCheckMapper.existsChatBanByChatId(item.getChatId())) {
                    item.setState(3);
                }
                boolean whetherJoinBzGroup = robotRewardFlowService.whetherJoinBzGroup(item.getWalletAddr());
                if (whetherJoinBzGroup) {
                    item.setBzTaskFinishState(1);
                } else {
                    item.setBzTaskFinishState(0);
                }
            });
        }
        return PageInfo.of(list);
    }

    @Override
    public RobotTaskCheck getRobotTaskCheckById(int id) {
        RobotTaskCheck robotTaskCheck = robotTaskCheckMapper.getRobotTaskCheckById(id);
        if (null != robotTaskCheck) {
            String chatId = robotTaskCheck.getChatId();
            if (null != robotTaskCheckMapper.existsChatBanByChatId(chatId)) {
                robotTaskCheck.setState(3);
            }
            robotTaskCheck.setTwitterAccountName(robotTaskCheckMapper.getTwitterAccountNameByChatId(chatId));
            List<String> groupLinkList = chatLinkService.getChatLinkListByChatIdAndLinkCategory(chatId, 1);
            if (!CollectionUtils.isEmpty(groupLinkList)) {
                robotTaskCheck.setGroupShareLink(groupLinkList);
            }
            List<String> twitterLinkList = chatLinkService.getChatLinkListByChatIdAndLinkCategory(chatId, 2);
            if (!CollectionUtils.isEmpty(twitterLinkList)) {
                robotTaskCheck.setTwitterShareLink(twitterLinkList.get(0));
            }
            List<RobotTaskCheckContent> robotTaskCheckContentList = robotTaskCheckMapper.getRobotTaskCheckContentListByTaskCheckId(id);
            if (!CollectionUtils.isEmpty(robotTaskCheckContentList)) {
                int size = robotTaskCheckContentList.size();
                List<RobotCheckPic> robotCheckPicList = new ArrayList<>(size);
                RobotCheckPic robotCheckPic;
                List<RobotTaskCheckContent> robotTasList;
                Set<String> createAtSet = new HashSet<>(size);
                for (RobotTaskCheckContent robotTaskCheckContent : robotTaskCheckContentList) {
                    String createAtStr = TimeUtil.getLocalDateStr(robotTaskCheckContent.getCreatedAt(), TimeUtil.Y_M_D);
                    if (createAtSet.contains(createAtStr)) {
                        continue;
                    }
                    createAtSet.add(createAtStr);
                    robotCheckPic = new RobotCheckPic();
                    robotCheckPic.setCreateAt(createAtStr);
                    robotTasList = robotTaskCheckContentList.stream().filter(item ->
                            createAtStr.equals(TimeUtil.getLocalDateStr(item.getCreatedAt(), TimeUtil.Y_M_D))
                    ).collect(Collectors.toList());
                    List<String> picUrlList = new ArrayList<>(size);
                    robotTasList.forEach(items -> {
                        String picUrl = items.getPicUrl();
                        picUrlList.add(picUrl);
                    });
                    robotCheckPic.setPicUrlList(picUrlList);
                    robotCheckPicList.add(robotCheckPic);
                }
                createAtSet.clear();
                robotTaskCheck.setRobotCheckPicList(robotCheckPicList);
            }
        }
        return robotTaskCheck;
    }

    @Override
    public RobotTaskCheck getRobotTaskCheckByChatId(String chatId) {
        return robotTaskCheckMapper.getRobotTaskCheckByChatId(chatId);
    }

    @Override
    public RobotIndexVO getBalance() {
        RobotIndexVO robotIndexVO = new RobotIndexVO();
        String rewardBalance = "0";
        String xwcBalance = "0";
        boolean openWallet = requestWalletService.openWallet();
        if (openWallet) {
            rewardBalance = requestWalletService.getBalance();
            if (StringUtils.isBlank(rewardBalance)) {
                rewardBalance = "0";
            }
            xwcBalance = requestWalletService.getXwcBalance();
            if (StringUtils.isBlank(xwcBalance)) {
                xwcBalance = "0";
            }
        }
        robotIndexVO.setRewardBalance(rewardBalance);
        robotIndexVO.setXwcBalance(xwcBalance);
        String robotStatus = robotSystemService.getSystemValueBySystemKey(RewardKeyEnum.STOP_ROBOT.name());
        if (StringUtils.isBlank(robotStatus)) {
            robotStatus = "0";
        }
        robotIndexVO.setRobotStatus(Integer.parseInt(robotStatus));
        return robotIndexVO;
    }

    @Override
    public void pushMessage(RobotSendMessageVO robotSendMessageVO) {
        httpManager.sendReSendPhoto(Long.parseLong(robotSendMessageVO.getChatId()), robotSendMessageVO.getSendMessage());
    }

    @Override
    public void synNoticeCheckedUserJoinBzGroup() {
        log.info("通知以前已经审核的用户加入Bz群任务开始执行");
        long begin = System.currentTimeMillis();
        Set<String> chatIdList = robotTaskCheckMapper.getChatIdListWithNoJoinBzGroup("BZ");
        if (!CollectionUtils.isEmpty(chatIdList)) {
            String message = robotSystemService.getSystemValueBySystemKey(RewardKeyEnum.JOIN_BZ_GROUP_MESSAGE.name());
            chatIdList.forEach(chatId -> {
                httpManager.sendReSendPhoto(Long.parseLong(chatId), message);
            });
        }
        log.info("通知以前已经审核的用户加入Bz群任务结束执行，消耗：{}毫秒", System.currentTimeMillis() - begin);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = CommonConsts.TRANSACTION_MANAGER)
    public void autoFinishCheck() {
        // 获取未审核的记录
        List<RobotTaskCheck> robotTaskUnCheckList = robotTaskCheckMapper.getUnCheckList();
        if (!CollectionUtils.isEmpty(robotTaskUnCheckList)) {
            int finishTasks;
            String chatId;
            Integer id;
            for (RobotTaskCheck robotTaskUnCheck : robotTaskUnCheckList) {
                id = robotTaskUnCheck.getId();
                chatId = robotTaskUnCheck.getChatId();
                finishTasks = robotTaskCheckMapper.getFinishTaskNumsByChatId(chatId);
                // 必须任务完成为6个才能自动审核
                if (finishTasks >= 6) {
                    checkSuccess(chatId, id, 2);
                }

            }
        }

    }

    private void checkSuccess(String chatId, Integer id, int state) {
        String withdrawOff = robotSystemService.getSystemValueBySystemKey(RewardKeyEnum.WITHDRAW_OFF.name());
        if ("1".equals(withdrawOff)) {
            throw new BusinessException(ResultCode.MONEY_TRANSFER_OFF_ERROR);
        }
        int count = robotTaskCheckMapper.updateRobotTaskState(id, state, new Date());
        if (count > 0) {
            CheckFailure checkFailure = new CheckFailure();
            checkFailure.setChatId(chatId);
            List<CheckFailure> checkFailures = checkFailureMapper.select(checkFailure);
            if (!CollectionUtils.isEmpty(checkFailures)) {
                checkFailureMapper.delete(checkFailure);
            }
            // 第一步：给自己打400TP
            String walletAddress = robotTaskCheckMapper.getWalletAddressByTaskCheckId(id);
            String finishTaskReward = robotSystemService.getSystemValueBySystemKey(RewardKeyEnum.FINISH_TASK_REWARD.name());
            boolean existRobotRewardFlow = robotRewardFlowService.existRobotRewardFlowByWalletAddressAndAmount(walletAddress, finishTaskReward);
            if (!existRobotRewardFlow) {
                // 插入奖励流水
                RobotRewardFlow robotRewardFlow = new RobotRewardFlow();
                robotRewardFlow.setWalletAddress(walletAddress);
                robotRewardFlow.setAmount(finishTaskReward);
                robotRewardFlow.setSerialNo("RD" + SnowFlakeIdUtil.defaultId());
                robotRewardFlow.setRewardFlowQuery(0);
                int robotRewardFlowCount = robotRewardFlowService.insertRobotRewardFlow(robotRewardFlow);
                if (robotRewardFlowCount > 0) {
                    requestWalletService.transferAmountToAddr(walletAddress, finishTaskReward);
                }
            }
            // 第二步：我的被邀请的人先比我审核通过，我还没审核，这时我审核成功就可以获取到邀请人的100Tp奖励
            // 如果我为代理人，那么我邀请的人审核成功我就获取不到奖励
            Integer agentState = robotTaskCheckMapper.getAgentStateById(id);
            Set<String> invitedWalletAddressList;
            int finishTaskNums;
            Integer recentState;
            int taskNums = robotTaskCheckMapper.getTaskNums();
            String invitedFriendFinishTaskReward = robotSystemService.getSystemValueBySystemKey(RewardKeyEnum.INVITE_FRIENDS_FINISH_TASK_REWARD.name());
            if (null == agentState || agentState != 1) {
                invitedWalletAddressList = robotInviteService.getInvitedWalletAddressListByWalletAddress(walletAddress);
                if (!CollectionUtils.isEmpty(invitedWalletAddressList)) {
                    int invitedFriendPersons = invitedWalletAddressList.size();
                    // 邀请人数100人以内邀请奖励为100，超过100人邀请奖励为200
                    if (invitedFriendPersons > 100) {
                        invitedFriendFinishTaskReward = "200";
                    }
//                        boolean existInviteRobotRewardFlow = robotRewardFlowService.existRobotRewardFlowByWalletAddressAndAmount(walletAddress, invitedFriendFinishTaskReward);
                    for (String invitedWalletAddress : invitedWalletAddressList) {
                        finishTaskNums = robotTaskCheckMapper.getFinishTaskNumsByInviterWalletAddress(invitedWalletAddress);
                        recentState = robotTaskCheckMapper.getRecentStateByInviterWalletAddress(invitedWalletAddress);
                        if (null == recentState) {
                            recentState = 0;
                        }
                        if (finishTaskNums == taskNums && recentState == 2) {
//                                if (!existInviteRobotRewardFlow) {
                            // 插入奖励流水
                            RobotRewardFlow inviteRobotRewardFlow = new RobotRewardFlow();
                            inviteRobotRewardFlow.setWalletAddress(walletAddress);
                            inviteRobotRewardFlow.setAmount(invitedFriendFinishTaskReward);
                            inviteRobotRewardFlow.setSerialNo("RD" + SnowFlakeIdUtil.defaultId());
                            int inviteRobotRewardFlowCount = robotRewardFlowService.insertRobotRewardFlow(inviteRobotRewardFlow);
                            if (inviteRobotRewardFlowCount > 0) {
                                requestWalletService.transferAmountToAddr(walletAddress, invitedFriendFinishTaskReward);
//                                    break;
                            }
//                                }
                        }
                    }
                }
            }
            // 第三步：给邀请人的钱包地址打100TP
            // 检查邀请人任务是否已完成并且审核记录是否成功，任务已完成才能获得100TP
            Set<String> inviterWalletAddressList = robotInviteService.getInviteWalletAddressByWalletAddress(walletAddress);
            if (!CollectionUtils.isEmpty(inviterWalletAddressList)) {
//                        boolean existInviteRobotRewardFlow;
                RobotRewardFlow inviteRobotRewardFlow;
                int inviteRobotRewardFlowCount;
                for (String inviterWalletAddress : inviterWalletAddressList) {
                    agentState = robotTaskCheckMapper.getAgentStateByWalletAddress(inviterWalletAddress);
                    if (null == agentState || agentState != 1) {
                        invitedWalletAddressList = robotInviteService.getInvitedWalletAddressListByWalletAddress(inviterWalletAddress);
                        // 邀请人数100人以内邀请奖励为100，超过100人邀请奖励为200
                        if (invitedWalletAddressList.size() > 100) {
                            invitedFriendFinishTaskReward = "200";
                        }
                        finishTaskNums = robotTaskCheckMapper.getFinishTaskNumsByInviterWalletAddress(inviterWalletAddress);
                        recentState = robotTaskCheckMapper.getRecentStateByInviterWalletAddress(inviterWalletAddress);
                        if (null == recentState) {
                            recentState = 0;
                        }
                        if (finishTaskNums == taskNums && recentState == 2) {
//                                existInviteRobotRewardFlow = robotRewardFlowService.existRobotRewardFlowByWalletAddressAndAmount(inviterWalletAddress, invitedFriendFinishTaskReward);
//                                if (!existInviteRobotRewardFlow) {
                            // 插入奖励流水
                            inviteRobotRewardFlow = new RobotRewardFlow();
                            inviteRobotRewardFlow.setWalletAddress(inviterWalletAddress);
                            inviteRobotRewardFlow.setAmount(invitedFriendFinishTaskReward);
                            inviteRobotRewardFlow.setSerialNo("RD" + SnowFlakeIdUtil.defaultId());
                            inviteRobotRewardFlowCount = robotRewardFlowService.insertRobotRewardFlow(inviteRobotRewardFlow);
                            if (inviteRobotRewardFlowCount > 0) {
                                requestWalletService.transferAmountToAddr(inviterWalletAddress, invitedFriendFinishTaskReward);
                            }
//                                }
                        }
                    }

                }
            }

        }
        // 机器人推送给用户加入https://t.me/Bzplan_XWC的相关消息
        httpManager.sendReSendPhoto(Long.parseLong(chatId), robotSystemService.getSystemValueBySystemKey(RewardKeyEnum.JOIN_BZ_GROUP_MESSAGE.name()));
    }

    @Value("${execute.task.bot.name}")
    private String executeTaskBotName;

    @Override
    public String getSponsoredLinks(String chatId) {
        return "https://t.me/" + executeTaskBotName + "?start=" + robotTaskCheckMapper.getWalletAddressByChatId(chatId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = CommonConsts.TRANSACTION_MANAGER)
    public int setOrCancelAgent(AgentVO agentVO) {
        Integer id = agentVO.getId();
        Integer existsRobotTaskCheck = robotTaskCheckMapper.existsRobotTaskCheckById(id);
        if (null != existsRobotTaskCheck) {
            Integer agentState = agentVO.getAgentState();
            // 取消代理人
            if (agentState == 0) {
                // 1、删除用户领取的TP数记录
//                robotTaskCheckMapper.deleteAgentReceiveIncomeByRobotCheckId(id);
                List<Integer> robotInviteIdList = robotInviteService.getRobotInviteIdListByRobotCheckId(id);
                // 2、重置用户邀请人记录状态
                if (!CollectionUtils.isEmpty(robotInviteIdList)) {
                    robotInviteService.patchCancelRobotInviteRewardReset(robotInviteIdList);
                }
            }
            RobotTaskCheck robotTaskCheck = new RobotTaskCheck();
            robotTaskCheck.setId(id);
            robotTaskCheck.setAgentState(agentState);
            robotTaskCheck.setUpdatedAt(new Date());
            return robotTaskCheckMapper.updateByPrimaryKeySelective(robotTaskCheck);
        }
        return 0;
    }

    @Override
    public PageInfo<AgentRankVO> getAgentRankListByPage(AgentRankQO agentRankQO) {
        Integer pageNum = agentRankQO.getPageNum();
        Integer pageSize = agentRankQO.getPageSize();
        PageHelper.startPage(pageNum, pageSize);
        List<AgentRankVO> list = robotTaskCheckMapper.getAgentRankListByPage(agentRankQO);
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(agentRankVO -> {
                // 获取总TP收益和未领取的TP数
                int tpTotalIncome = 0;
                // 获取邀请人数
                Integer invitedPersonCount = agentRankVO.getInvitePersonCount();
                if (null != invitedPersonCount) {
                    if (invitedPersonCount >= 1 && invitedPersonCount <= 10) {
                        // 1-10人  每人70TP
                        tpTotalIncome = invitedPersonCount * 70;
                    }
                    if (invitedPersonCount >= 11 && invitedPersonCount <= 30) {
                        // 11-30人  每人180TP
                        tpTotalIncome = 700 + invitedPersonCount * 180;
                    }
                    if (invitedPersonCount >= 31 && invitedPersonCount <= 50) {
                        // 31-50人  每人300TP
                        tpTotalIncome = 700 + 3600 + invitedPersonCount * 300;
                    }
                    if (invitedPersonCount >= 51) {
                        // 50人以上 每人600TP
                        tpTotalIncome = 700 + 3600 + 6000 + invitedPersonCount * 600;
                    }
                } else {
                    agentRankVO.setInvitePersonCount(0);
                }
//                Integer receivedTpAmount = agentRankVO.getReceivedTpAmount();
//                if (null == receivedTpAmount) {
//                    receivedTpAmount = 0;
//                }
                // 获取该用户已经领取的累计TP数目
                Integer totalReceivedTpAmount = robotTaskCheckMapper.getTotalReceivedTpAmountByChatId(agentRankVO.getChatId());
                if (null == totalReceivedTpAmount) {
                    agentRankVO.setReceivedTpAmount(0);
                } else {
                    agentRankVO.setReceivedTpAmount(totalReceivedTpAmount);
                }
                agentRankVO.setUnReceivedTpAmount(tpTotalIncome);
                // 未领取收益
              /*  if (tpTotalIncome > receivedTpAmount) {
                    agentRankVO.setUnReceivedTpAmount(tpTotalIncome - receivedTpAmount);
                } else {
                    agentRankVO.setUnReceivedTpAmount(0);
                }*/
            });
        }
        return PageInfo.of(list);
    }

    @Override
    public PageInfo<InviterVO> getInviterListByPage(InviterQO inviterQO) {
        PageHelper.startPage(inviterQO.getPageNum(), inviterQO.getPageSize());
        List<InviterVO> list = robotTaskCheckMapper.getInviterList(inviterQO.getChatId());
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(item -> {
                if (null != item) {
                    String userName = item.getUserName();
                    if (StringUtils.isNotBlank(userName)) {
                        item.setTelegramAccountName(userName);
                    } else {
                        String firstName = item.getFirstName();
                        String lastName = item.getLastName();
                        if (StringUtils.isNotBlank(firstName)) {
                            if (StringUtils.isNotBlank(lastName)) {
                                item.setTelegramAccountName(firstName + lastName);
                            } else {
                                item.setTelegramAccountName(firstName);
                            }
                        } else {
                            if (StringUtils.isNotBlank(lastName)) {
                                item.setTelegramAccountName(lastName);
                            }
                        }
                    }
                }
            });
        }
        return PageInfo.of(list);
    }


}
